package com.gluck.cases.core.block.impl;

import com.gluck.cases.common.utils.enums.BizSerErrorEnum;
import com.gluck.cases.common.utils.utils.AssertUtil;
import com.gluck.cases.core.block.RoleBlock;
import com.gluck.cases.common.utils.dal.dao.RoleMapper;
import com.gluck.cases.core.modal.assemble.RoleAssemble;
import com.gluck.cases.core.modal.dto.RoleDTO;
import com.gluck.cases.core.modal.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @ClassName RoleBlockImpl
 * @Desc RoleBlockImpl 实现类
 * @Author I am Gluck
 * @Date 2022/5/17 - 8:04 下午
 **/
@Service
public class RoleBlockImpl implements RoleBlock {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Role> findAdminRoleByUsername(String username) {
        return roleMapper.findAdminRoleByUsername(username);
    }

    @Override
    public Role addRole(RoleDTO roleDTO) {
        Role roleByRoleName = roleMapper.findRoleByRoleName(roleDTO.getName());
        AssertUtil.isTrue(!Objects.isNull(roleByRoleName), BizSerErrorEnum.DATA_UNIQUE_ERROR);
        Role role = RoleAssemble.roleDTOConvertRole(roleDTO);
        int insert = roleMapper.insertSelective(role);
        AssertUtil.isTrue(insert == 0 ? true : false, BizSerErrorEnum.INSERT_ERROR);
        return role;
    }

    @Override
    public Role updateRole(RoleDTO roleDTO) {
        Role roleByRoleName = roleMapper.findRoleByRoleName(roleDTO.getName());
        AssertUtil.isTrue(Objects.isNull(roleByRoleName), BizSerErrorEnum.DATA_NOT_FOUND);
        Role role = RoleAssemble.roleDTOConvertRole(roleDTO);
        int update = roleMapper.updateByPrimaryKeySelective(role);
        AssertUtil.isTrue((update == 0 ? true : false), BizSerErrorEnum.UPDATE_ERROR);
        return role;
    }

    @Override
    public Integer deleteRole(RoleDTO roleDTO) {
        int delete = roleMapper.deleteByPrimaryKey(roleDTO.getId());
        AssertUtil.isTrue(delete == 0 ? true : false, BizSerErrorEnum.DELETE_ERROR);
        return delete;
    }
}
